/****************************************
Designed by WHD in LinAn.2023
恩格马加密，加密解密都是调用 Encryptor::encrypt
构造函数中的 startIndex 是加密算子链表的起始下标
****************************************/
#ifndef ENIGMAENCRYPTOR_H
#define ENIGMAENCRYPTOR_H

#include "encryptor.h"
#include "enigmasecretlist.h"
#include <QDebug>

class EnigmaEncryptor : public Encryptor
{
public:
    EnigmaEncryptor(unsigned char startIndex)
        : Encryptor()
        , startIndex_(startIndex)
        , nowIt_(EnigmaSecretList::CSLIST_SECRET.begin() + startIndex % EnigmaSecretList::CSLIST_SECRET.size())
    {
    }

    virtual QByteArray encrypt(const QByteArray& data) override {return enigmaEncrypt(data);}
    virtual QByteArray decrypt(const QByteArray& data) override {return enigmaEncrypt(data);}

    unsigned char getStartIndex() {return startIndex_;}
    virtual void reInit() override {nowIt_ = EnigmaSecretList::CSLIST_SECRET.begin() + (startIndex_ % EnigmaSecretList::CSLIST_SECRET.size());}

private:
    QByteArray enigmaEncrypt(const QByteArray&);

    inline void getChar(char oldC, char& toC)
    {
        toC = nowIt_->at(oldC & 0xff);

        if (nowIt_ == EnigmaSecretList::CSLIST_SECRET.end())
            nowIt_ = EnigmaSecretList::CSLIST_SECRET.begin();
        else
            ++nowIt_;
    }

    const unsigned char startIndex_;
    QVector<QVector<unsigned char>>::const_iterator nowIt_;
};

#endif // ENIGMAENCRYPTOR_H
